/*
 * @Author: silas 
 * @Date: 2021-05-17 15:11:55 
 * @Last Modified by: silas
 * @Last Modified time: 2021-05-28 15:20:24
 */
<template>
    <div class="tobBtoC">
        <div class="contentTopTitle">
            <div class="title">收入预估录入</div>
        </div>
        <div>
            <el-form
                :inline="true"
                :model="form"
                label-width="60px"
                class="formList"
            >
                <el-form-item label="账期" style="width: 20%" >
                    <el-date-picker
                        v-model="form.time"
                        type="month"
                        placeholder="选择账期"
                        value-format="yyyyMM"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item label="版本集合" style="width: 20%">
					<el-select v-model="form.version">
						<el-option v-for="(it, i) in version" :key="i" :label="it.label" :value="it.value"></el-option>
					</el-select>
                </el-form-item>
                <el-form-item  style="width: 34%">
                    <el-button
                        style="margin-left: 20px"
                        size="mini"
                        type="primary"
                        @click="handle_search"
                        >查询</el-button
                    >
					<el-button @click="handle_down()" size="mini"
						>模板下载</el-button
					>
					<el-button
                    type="orange"
                    @click="
                        dialogVisible = true;
                        importForm.year = '';
                        importForm.typeId = '';
                        importForm.version = '';
                        fileList = [];
                    "
                    size="mini"
                    >导入</el-button
                >
					<el-button size="mini" type="orange" @click="handle_export">
						导出
					</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="table-content clearfix">
            <p class="g-unit">单位: 万元</p>
            <div class="content" style="margin-top: 0;">
                <div class="tableBox">
                    <el-table
						id="table"
                        v-loading="tableLoading"
                        :data="tableData"
                        style="width: 100%"
                        class="tableTh28"
                        border
                        stripe
                        ref="table"
                    >
                        <el-table-column min-width="90" label="收入账期" prop="acctMonth" />
                        <el-table-column min-width="90" label="填报版本" prop="version" />
                        <el-table-column min-width="90" label="填报单位" prop="companyName" />
                        <el-table-column min-width="110" label="填报部门" prop="departName" />
                        <el-table-column min-width="90" label="填报人员" prop="userName" />

                        <el-table-column v-for="(it, i) in titles" :key="i" :prop="it.horizonIndexId" :label="it.label">
                            <el-table-column v-for="(item, index ) in it.origin" :key="index" :label="item.horizonIndexName" :prop="item.horizonIndexId"></el-table-column>
                        </el-table-column>
                        <!-- <el-table-column min-width="90" label="主营收入" prop="HA006001" />
                       
						<el-table-column label="基本面收入">
									<el-table-column min-width="110" label="基本面收入总计" prop="HA006002"></el-table-column>
									<el-table-column min-width="110" label="其中：移动业务收入" prop="HA006003"></el-table-column>
									<el-table-column min-width="110" label="其中：行业短信结算" prop="HA006004"></el-table-column>
									<el-table-column min-width="110" label="其中：流量漫游结算" prop="HA006005"></el-table-column>
									<el-table-column min-width="110" label="宽带业务收入" prop="HA006006"></el-table-column>
									<el-table-column min-width="110" label="双线收入" prop="HA006007"></el-table-column>
									<el-table-column min-width="110" label="物联网收入" prop="HA006008"></el-table-column>
						</el-table-column>
						<el-table-column label="DICT">
									<el-table-column min-width="110" label="DICT收入总计" prop="HA006009"></el-table-column>
									<el-table-column min-width="110" label="其中：ICT收入" prop="HA006010"></el-table-column>
									<el-table-column min-width="110" label="其中：IDC收入" prop="HA006011"></el-table-column>
									<el-table-column min-width="110" label="其中：云业务收入（仅省云网部需要填）" prop="HA006012"></el-table-column>
						</el-table-column>
						<el-table-column label="分公司人工收入">
									<el-table-column min-width="110" label="预估导入值（主营收入预估值的其中数）" prop="HA006015"></el-table-column>
									<el-table-column min-width="110" label="最大可能导入值" prop="HA006016"></el-table-column>
									<el-table-column min-width="110" label="最小可能导入值" prop="HA006017"></el-table-column>
						</el-table-column>
						<el-table-column min-width="90" label="移动出账用户" prop="HA006013" />
                        <el-table-column min-width="90" label="宽带计费用户" prop="HA006014" /> -->
						<el-table-column label="操作" v-if="!isExport">
							<template slot-scope="scope">
								<el-link type="primary" @click="handle_del(scope.row,scope.$index)">删除</el-link>
							</template>
						</el-table-column>
                    </el-table>
                </div>
            </div>
        </div>
		 <el-dialog
            title="导入文件"
            append-to-body
            :visible.sync="dialogVisible"
            width="450px"
        >
            <el-form :model="importForm" ref="importForm" :rules="rules">
                <el-form-item label="账期" prop="year" label-width="80px">
                    <el-date-picker
                        v-model="importForm.year"
                        type="month"
                        size="mini"
                        placeholder="选择时间"
                        value-format="yyyyMM"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item
                    label-width="80px"
                    label="版本"
                    prop="version"
                >
                    <el-select v-model="importForm.version" size="mini" clearable style="width: 220px">
                        <el-option v-for="(it, i) in importVersion" :key="i" :label="it.label" :value="it.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item
                    label-width="80px"
                    label="类别"
                    prop="typeId"
                >
                    <el-select v-model="importForm.typeId" size="mini" clearable style="width: 220px">
                        <el-option v-for="(it, i) in typeslist" :key="i" :label="it.typeName" :value="it.typeId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="上传文件" prop="file">
                    <el-upload
                        size="mini"
                        :limit="1"
                        accept=".xls, .xlsx"
                        class="avatar-uploader"
                        :auto-upload="false"
                        :file-list="fileList"
                        :on-change="changeFile"
                        action
                    >
                        <el-button size="mini" type="primary"
                            >点击上传</el-button
                        >
                    </el-upload>
                </el-form-item>
            </el-form>

            <div slot="footer">
                <div class="dialog-footer">
                    <el-button
                        size="mini"
                        type="primary"
                        @click="handle_import()"
                        >确定</el-button
                    >
                    <el-button size="mini" @click="dialogVisible = false"
                        >取消</el-button
                    >
                </div>
            </div>
        </el-dialog>
		
    </div>
</template>

<script>
import prefixAPI from "@/api/prefixAPI";
import { getCookie } from "@/common/js/cookie";
import { getSessionStorage } from "@/common/js/storage";
import { $budgetAPI } from "@/api";
import FileSaver from 'file-saver';
import XLSX from 'xlsx';
import costRevenueVue from '../showPdf/costRevenue.vue';
export default {
    name: "lightEva",
    data() {
        return {
            form: {
                time: '',
				version: '24',
            },
            tableData: [],
            tableLoading: false,
			version: [{label: '24日', value: '24'}, {label: '28日', value: '28'}],
            importForm: {
                year: "",
                version: "",
                typeId: '',
            },
            importVersion: [{label: '24日', value: '24'}, {label: '28日', value: '28'}],
            dialogVisible: false,
            fileList: [],
            rules: {
                year: [
                    { required: true, message: "请选择时间", trigger: "blur" },
                ],
                version: [
                    { required: true, message: "请选择版本", trigger: "blur" },
                ],
                typeId: [
                    { required: true, message: "请选择类别", trigger: "blur" },
                ]
            },
            typeslist: [],
            titles: [],
            isExport: false,
			
        };
    },
    mounted() {
		this.init();
	},
    methods: {
        async init() {
            let that = this;

            that.accountInfo = JSON.parse(getSessionStorage("accountInfo"));
            that.form.areaId = that.accountInfo.areaId;
            that.form.time = that.moment().format("YYYYMM");
            that.getTypes()
			that.getData();
        },
        getTypes() {
            $budgetAPI.getRecordTypeList({}, res=> {
                this.typeslist = res.content;
            })
        },
        getData() {
            var that = this, title;

            that.tableLoading = true;
            $budgetAPI.getEstimateDataList(
                {
                    acctMonth: that.form.time,
					version: that.form.version,
                },
                (res) => {
					that.tableData = [];
                    if (res && res.code == 0) {
						res.content.data.map(it=> {
							it.detailList.map(item => {
								it[item.indexId] = item.indexValue
							})
						})
                        title = that.mergeTitles(res.content.titles, 'class1');
                        title.map(it => {
                            if(it.origin.length == 1) {
                                it.origin = []
                            }
                        })
                        that.titles = title
                        that.tableData = res.content.data;
                        
                    }
                    that.tableLoading = false;
                }
            );
        },
        handle_search() {
			// if(!this.form.time || !this.form.fcDate) {
			// 	this.$message.error("请选择账期和版本");
			// 	return false
			// }
            this.getData();
        },
		handle_time(val) {
			this.form.time = val;
			this.form.fcDate = '';
			this.getFC(val);
		},
		handle_export() {
			var xlsxParam = {
                raw: true,
            }; //转换成excel时，使用原始的格式，这样导出的时候数字过长不会变成科学计数法


            if(!this.tableData.length) {
				this.$message.error('暂无数据可导出');
				return false
			}
            this.isExport = true;
            setTimeout(()=>{
                let workbook = XLSX.utils.book_new();
                let ws1 = XLSX.utils.table_to_sheet(
                    document.querySelector("#table"),
                    xlsxParam
                );
                XLSX.utils.book_append_sheet(workbook, ws1, "收入预估录入");
                let wbout = XLSX.write(workbook, {
                    bookType: "xlsx",
                    bookSST: true,
                    type: "array",
                });
                
                this.loading = this.$loading({
                    lock: true,
                    text: '正在',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                try {
                    FileSaver.saveAs(
                        new Blob([wbout], {
                            type: 'application/octet-stream;charset=utf-8"',
                        }),
                        "收入预估录入-" + this.form.time + "-" + this.form.version + "日.xlsx"
                    );
                    this.loading.close();
                    this.isExport = false;
                } catch (e) {
                    if (typeof console !== "undefined") console.log(e, wbOut);
                }
            }, 200)
            
		},
        handle_del(row) {
            var that = this;

            that.$confirm("是否删除?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                $budgetAPI.getDeleteRecord(
                    {
                        recordId: row.recordId,
                        token: getCookie("token"),
                    },
                    (res) => {
                        if (res.code == 0) {
                            this.$message({
                                type: "success",
                                message: "删除成功!",
                            });
                        } else {
                            this.$message({
                                type: "error",
                                message: res.message,
                            });
                        }
                        that.getData();
                    }
                );
            });
        },
		handle_down() {
            var token = getCookie("token");

            window.location.href =
                prefixAPI.hp +
                "/api/incomeEstimateImport/downTemplate?&token=" +
                token;
        },
        // 批量导入上传文件传递数据
        changeFile(file, fileList) {
            this.fileList = fileList;
            this.param = new FormData();
            this.param.append("file", file.raw);
        },
        // 导入
        handle_import(type) {
            var that = this;

            that.$refs["importForm"].validate((valid) => {
                if (valid) {
                    if (that.fileList.length == 0) {
                        that.$message({
                            message: "请选择需要上传的文件",
                            type: "warning",
                        });
                        return false;
                    }
                    that.param.append(
                        "version",
                        that.importForm.version
                    );
                    that.param.append("token", getCookie("token"));
                    that.param.append("acctMonth", that.importForm.year);
                    that.param.append("typeId", that.importForm.typeId);
                    $budgetAPI.importIncomeEstimateData(
                        that.param,
                        (res) => {
                            if (res.code == 0) {
                                that.$message({
                                    message: "导入成功",
                                    type: "success",
                                });
                                that.getData();
                            } else {
                                that.$message.error(res.message);
                            }
                            that.dialogVisible = false;
                        },
                        (err) => {
                            that.dialogVisible = false;
                        }
                    );
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        mergeTitles(data, type) {
            let tempArr = [];
            let afterData = [];
            for (let i = 0; i < data.length; i++) {
                if (tempArr.indexOf(data[i][type]) === -1) {
                afterData.push({
                    label: data[i][type],
                    horizonIndexId: data[i].horizonIndexId,
                    origin: [data[i]]
                });
                tempArr.push(data[i][type]);
            } else {
                    for (let j = 0; j < afterData.length; j++) {
                        if (afterData[j].label == data[i][type]) {
                            afterData[j].origin.push(data[i]);
                            break;
                        }
                    }
                }    
            }
            return afterData;
        },
        
		// hanlde_version(val) {
		// 	this.form.fcDate = val;
		// 	this.getData();
		// }
    },
};
</script>

<style lang="scss" scoped>
.remark {
    padding-top: 5px;
    text-align: left;
    .attention {
        font-weight: bold;
    }
}
.table-content {
    .table-header {
        display: flex;
        justify-content: space-between;
        .table-title {
            font-size: 14px;
            font-weight: bold;
            height: 30px;
            line-height: 30px;
            span {
                display: inline-block;
                width: 5px;
                height: 5px;
                background-color: #418ee9;
                border-radius: 1000%;
                overflow: hidden;
                margin-right: 10px;
                margin-bottom: 3px;
            }
        }
    }
    .content {
        margin-top: 15px;
    }
}
</style>
